import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/store/auth'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/components/auth/Login.vue'),
    meta: { requiresGuest: true },
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/components/auth/Register.vue'),
    meta: { requiresGuest: true },
  },
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/UserProfile.vue'),
        meta: { requiresAuth: true },
      },
  {
    path: '/properties',
    name: 'Properties',
    component: () => import('@/views/Properties.vue'),
  },
  {
    path: '/properties/:id',
    name: 'PropertyDetail',
    component: () => import('@/views/PropertyDetail.vue'),
  },
  {
    path: '/publish-property',
    name: 'PublishProperty',
    component: () => import('@/views/PublishProperty.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/my-properties',
    name: 'MyProperties',
    component: () => import('@/views/MyProperties.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/appointments',
    name: 'Appointments',
    component: () => import('@/views/Appointments.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/contracts',
    name: 'Contracts',
    component: () => import('@/views/Contracts.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/requirements',
    name: 'Requirements',
    component: () => import('@/views/Requirements.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/feedback',
    name: 'Feedback',
    component: () => import('@/views/Feedback.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/messages',
    name: 'Messages',
    component: () => import('@/views/Messages.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/contact',
    name: 'Contact',
    component: () => import('@/views/Contact.vue'),
    meta: { requiresAuth: true },
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 如果有token但没有用户信息，先获取用户信息
  if (localStorage.getItem('token') && !authStore.user) {
    await authStore.fetchUserInfo()
  }
  
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    next('/login')
  } else if (to.meta.requiresGuest && authStore.isLoggedIn) {
    next('/properties')
  } else {
    next()
  }
})

export default router